import {Component, EventEmitter, Input, Output} from '@angular/core';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.scss']
})
export class CalculatorComponent {

  @Input() bid: any = {};
  @Output() closeEmit = new EventEmitter<any>();

  // 计算器键盘值
  public keyboard = ['7', '8', '9', '4', '5', '6', '1', '2', '3'];
  // 计算器输入金额
  public inputResult = '';
  // 计算器计算收益
  public computedResult = 0;

  constructor() {
  }

  // 计算器输入金额
  inputVal(val) {
    const resInt = parseInt(this.inputResult + val);
    if (!isNaN(resInt)) {
      this.inputResult = '' + Math.min(resInt, this.bid.amount);
      this.computeProfit();
    } else {
      this.inputResult = '';
      this.computedResult = 0;
    }
  }

  // 计算器消去金额
  backVal() {
    if (this.inputResult) {
      this.inputResult = this.inputResult.slice(0, -1);
      this.computeProfit();
    }
  }

  // 计算收益
  private computeProfit() {
    const resInt = parseInt(this.inputResult);
    if (!isNaN(resInt)) {
      let unit = 12; // 默认期限单位为月
      if (this.bid['period_unit'] === 1) { // 如果期限单位为天
        unit = 365;
      }
      this.computedResult = resInt * (this.bid['apr'] / 100) * this.bid['period'] / unit;
    } else {
      this.computedResult = 0;
    }
  }

  closeCalculator() {
    // 发送关闭事件
    this.closeEmit.emit();
    // 重置输入和计算结果
    this.inputResult = '';
    this.computeProfit();
  }

}
